package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyServiceImpl implements IStrategyService {
    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private MongoTemplate mongoTemplate;//可以操作数据库

    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        strategyRepository.save(strategy);
    }


    @Override
    public void updateInfo(Strategy strategy) {

    }

    @Override
    public void update(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public Strategy get(String id) {
        Optional byId = strategyRepository.findById(id);
//强转
        return (Strategy) byId.orElse(null);//如果是空是就返回空值,否则返回对象
    }

    @Override
    public List<Strategy> listAll() {
        List<Strategy> strategys = strategyRepository.findAll();
        return strategys;
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }


    /**
     * 抽取的新增/修改方法
     * @param strategy
     */
    @Override
    public void saveOrUpdate(Strategy strategy) {
        if (!StringUtils.hasLength(strategy.getId())) {
            this.save(strategy);
        } else {
//            //修改操作
            this.update(strategy);
        }
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        //查询对象
        Query query = new Query();
        //查询出总数条数
        long rows = mongoTemplate.count(query, Strategy.class);
        if (rows == 0) {
            return  Page.empty();//如果总数条数是0,就返回空集合
        }
        //分页对象(设置当前页从0开始算,还有页面显示条数,按sequence这个列正序排列 )  
        //  Sort.Direction.ASC,表示按正序排列表格
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "sequence");
        //给查询对象
        query.with(pageable);
        List<Strategy> list = mongoTemplate.find(query, Strategy.class);

        return  new PageImpl<Strategy>(list,pageable,rows);//相当于pageResult对象

    }

    @Override
    public void input(String id) {

    }

    @Override
    public Strategy getstrategy(String id) {

        return this.get(id);
    }

}
